package com.ts.common.service.impl;

import com.ts.common.dao.WaterCodeMapper;
import com.ts.common.domain.WaterCode;
import com.ts.common.service.IWaterCodeService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;

/**
 * 流水码 服务层
 *
 * @author qinguidong
 * @date 2020/12/11
 */
@Service
public class WaterCodeServiceImpl implements IWaterCodeService {

    @Resource
    private WaterCodeMapper waterCodeMapper;
    @Resource
    private IWaterCodeService iWaterCodeService;

    /**
     * @pre 前缀
     * @type 类型 可以直接是数据表名称
     * @length 生产流水码长度
     * 生成流水码
     * 位数不够前补0
     */
    @Override
    public String generate(String pre, String type, int length) {
        return pre + generate(type, length);
    }

    /**
     * 生成流水码
     * 位数不够前补0
     */
    @Override
    public String generate(String type, int length) {
        Integer code = iWaterCodeService.generate(type);
        // 0 代表前面补充0
        // length 代表长度为 length
        // d 代表参数为正数型
        return String.format("%0" + length + "d", code);
    }

    /**
     * 生成流水码
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer generate(String type) {

        //先更新，数据库加行锁
        addOrEdit(type);
        WaterCode entity = waterCodeMapper.selectByType(type);
        return entity.getCurrent();
    }

    /**
     * 新增或编辑
     */
    private int addOrEdit(String type) {

        WaterCode entity = new WaterCode();
        entity.setType(type)
                .setCurrent(1)
                .setCreateTime(new Date())
                .setModifyTime(new Date());
        return waterCodeMapper.insertOrUpdate(entity);
    }
}
